﻿function GetWindLevel(windSpeed) {
    if (windSpeed == null || windSpeed == "--") {
        return "--";
    }
    else if (windSpeed >= 0 && windSpeed <= 0.2) {
        return "无风";
    }
    else if (windSpeed > 0.2 && windSpeed <= 1.5) {
        return "软风";
    }
    else if (windSpeed > 1.5 && windSpeed <= 3.3) {
        return "轻风";
    }
    else if (windSpeed > 3.3 && windSpeed <= 5.4) {
        return "微风";
    }
    else if (windSpeed > 5.4 && windSpeed <= 7.9) {
        return "和风";
    }
    else if (windSpeed > 7.9 && windSpeed <= 10.7) {
        return "劲风";
    }
    else if (windSpeed > 10.7 && windSpeed <= 13.8) {
        return "强风";
    }
    else if (windSpeed > 13.8 && windSpeed <= 17.1) {
        return "疾风";
    }
    else if (windSpeed > 17.1 && windSpeed <= 20.7) {
        return "大风";
    }
    else if (windSpeed > 20.7 && windSpeed <= 24.4) {
        return "烈风";
    }
    else if (windSpeed > 24.4 && windSpeed <= 28.4) {
        return "狂风";
    }
    else if (windSpeed > 28.4 && windSpeed <= 32.6) {
        return "暴风";
    }
    else if (windSpeed > 32.6) {
        return "飓风";
    }
}

function GetWindDirectionName(windDirection) {
    var const_正北 = 0, const_北东北 = 22.5, const_东北 = 45, const_东东北 = 67.5;
    var const_正东 = 90, const_东东南 = 112.5, const_东南 = 135, const_南东南 = 157.5;
    var const_正南 = 180, const_南西南 = 202.5, const_西南 = 225, const_西西南 = 247.5;
    var const_正西 = 270, const_西西北 = 292.5, const_西北 = 315, const_北西北 = 337.5;
    var const_360 = 360, const_HalfHorn = 11.25;
    if (windDirection == null || windDirection == "--") {
        return "--";
    }
    else if (windDirection > const_北东北 - 11.25 && windDirection < const_北东北 + 11.25) {
        return "北东北风";
    }
    else if (windDirection == const_北东北 + 11.25) {
        return "北东北风转东北风";
    }
    else if (windDirection > const_东北 - 11.25 && windDirection < const_东北 + 11.25) {
        return "东北风";
    }
    else if (windDirection == const_东北 + 11.25) {
        return "东北风转东东北风";
    }
    else if (windDirection > const_东东北 - 11.25 && windDirection < const_东东北 + 11.25) {
        return "东东北风";
    }
    else if (windDirection == const_东东北 + 11.25) {
        return "东东北风转东风";
    }
    else if (windDirection > const_正东 - 11.25 && windDirection < const_正东 + 11.25) {
        return "东风";
    }
    else if (windDirection == const_正东 + 11.25) {
        return "东风转东东南风";
    }
    else if (windDirection > const_东东南 - 11.25 && windDirection < const_东东南 + 11.25) {
        return "东东南风";
    }
    else if (windDirection == const_东东南 + 11.25) {
        return "东东南风转东南风";
    }
    else if (windDirection > const_东南 - 11.25 && windDirection < const_东南 + 11.25) {
        return "东南风";
    }
    else if (windDirection == const_东南 + 11.25) {
        return "东南风转南东南风";
    }
    else if (windDirection > const_南东南 - 11.25 && windDirection < const_南东南 + 11.25) {
        return "南东南风";
    }
    else if (windDirection == const_南东南 + 11.25) {
        return "南东南风转南风";
    }
    else if (windDirection > const_正南 - 11.25 && windDirection < const_正南 + 11.25) {
        return "南风";
    }
    else if (windDirection == const_正南 + 11.25) {
        return "南风转南西南风";
    }
    else if (windDirection > const_南西南 - 11.25 && windDirection < const_南西南 + 11.25) {
        return "南西南风";
    }
    else if (windDirection == const_南西南 + 11.25) {
        return "南西南风转西南风";
    }
    else if (windDirection > const_西南 - 11.25 && windDirection < const_西南 + 11.25) {
        return "西南风";
    }
    else if (windDirection == const_西南 + 11.25) {
        return "西南风转西西南风";
    }
    else if (windDirection > const_西西南 - 11.25 && windDirection < const_西西南 + 11.25) {
        return "西西南风";
    }
    else if (windDirection == const_西西南 + 11.25) {
        return "西西南风转西风";
    }
    else if (windDirection > const_正西 - 11.25 && windDirection < const_正西 + 11.25) {
        return "西风";
    }
    else if (windDirection == const_正西 + 11.25) {
        return "西风转西西北风";
    }
    else if (windDirection > const_西西北 - 11.25 && windDirection < const_西西北 + 11.25) {
        return "西西北风";
    }
    else if (windDirection == const_西西北 + 11.25) {
        return "西西北风转西北风";
    }
    else if (windDirection > const_西北 - 11.25 && windDirection < const_西北 + 11.25) {
        return "西北风";
    }
    else if (windDirection == const_西北 + 11.25) {
        return "西北风转北西北风";
    }
    else if (windDirection > const_北西北 - 11.25 && windDirection < const_北西北 + 11.25) {
        return "北西北风";
    }
    else if (windDirection == const_北西北 + 11.25) {
        return "北西北风转北风";
    }
    else if (windDirection > 360 - 11.25 && windDirection <= 360) {
        return "北风";
    }
    else if (windDirection >= 0 && windDirection < 11.25) {
        return "北风";
    }
    else if (windDirection == 11.25) {
        return "北风转北东北风"
    }
}


function Meteogram(config) {
    // Parallel arrays for the chart data, these are populated as the XML/JSON file
    // is loaded

    this.windDirections = [];
    this.windDirectionNames = [];
    this.windSpeeds = [];
    this.windSpeedNames = [];
    this.temperatures = [];
    this.rainfalls = [];
    this.timepoints = [];
    this.pressures = [];

    this.jsonData = config["JsonData"];    //数据源
    this.title = config["Title"];    //数据源
    this.timePointFormat = config["TimePointFormat"] || null;
    this.height = config["Height"] || null;
    this.width = config["width"] || null;
    this.container = config['Container'] || null;

    // Run
    this.initData();
}

Meteogram.prototype.windArrow = function (name) {
    var level,
        path;

    // The stem and the arrow head
    path = [
        'M', 0, 7, // base of arrow
        'L', -1.5, 7,
        0, 10,
        1.5, 7,
        0, 7,
        0, -10 // top
    ];

    level = $.inArray(name, ['无风', '软风', '轻风', '微风', '和风',
        '劲风', '强风', '疾风', '大风', '烈风', '狂风',
        '暴风', '飓风']);

    if (level === 0) {
        path = [];
    }

    if (level === 2) {
        path.push('M', 0, -8, 'L', 4, -8); // short line
    } else if (level >= 3) {
        path.push(0, -10, 7, -10); // long line
    }

    if (level === 4) {
        path.push('M', 0, -7, 'L', 4, -7);
    } else if (level >= 5) {
        path.push('M', 0, -7, 'L', 7, -7);
    }

    if (level === 5) {
        path.push('M', 0, -4, 'L', 4, -4);
    } else if (level >= 6) {
        path.push('M', 0, -4, 'L', 7, -4);
    }

    if (level === 7) {
        path.push('M', 0, -1, 'L', 4, -1);
    } else if (level >= 8) {
        path.push('M', 0, -1, 'L', 7, -1);
    }

    return path;
};

Meteogram.prototype.drawWindArrows = function (chart) {
    var meteogram = this;

    $.each(chart.series[0].data, function (i, point) {
        var sprite, arrow, x, y;

        // Draw the wind arrows
        x = point.plotX + chart.plotLeft + 7;
        y = chart.chartHeight - 90;
        if (meteogram.windDirectionNames[i] == null || meteogram.windDirectionNames[i] == "--" || meteogram.windSpeedNames[i] == null || meteogram.windSpeedNames[i] === '--') {
            return true;
        }
        else if (meteogram.windSpeedNames[i] === '无风') {
            arrow = chart.renderer.circle(x, y, 10).attr({
                fill: 'none'
            });
        } else {
            arrow = chart.renderer.path(
                meteogram.windArrow(meteogram.windSpeedNames[i])
            ).attr({
                rotation: parseInt(meteogram.windDirections[i], 10),
                translateX: x, // rotation center
                translateY: y // rotation center
            });
        }
        arrow.attr({
            stroke: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black',
            'stroke-width': 1.5,
            zIndex: 5
        })
        .add();

    });
};

Meteogram.prototype.drawBlocksForWindArrows = function (chart) {
    var xAxis = chart.xAxis[0],
        x,
        pos,
        max,
        isLong,
        isLast,
        i;

    for (pos = xAxis.min, max = xAxis.max, i = 0; pos <= max + 1; pos += 1, i += 1) {

        // Get the X position
        isLast = pos === max;
        x = Math.round(xAxis.toPixels(pos)) + (isLast ? 0.5 : -0.5);

        // Draw the vertical dividers and ticks

        chart.renderer.path(['M', x, chart.plotTop + chart.plotHeight,
            'L', x, chart.plotTop + chart.plotHeight + 32, 'Z'])
            .attr({
                'stroke': chart.options.chart.plotBorderColor,
                'stroke-width': 1
            })
            .add();
    }
};

Meteogram.prototype.tooltipFormatter = function (tooltip) {

    // Create the header with reference to the time interval
    var index = tooltip.points[0].point.index,
        ret = '<middle>' + tooltip.x + '</middle><br>';

    // Symbol text
    //ret += '<b>' + this.symbolNames[index] + '</b>';

    ret += '<table>';

    // Add all series
    Highcharts.each(tooltip.points, function (point) {
        var series = point.series;
        ret += '<tr><td><span style="color:' + series.color + '">\u25CF</span> ' + series.name +
            ': </td><td style="white-space:nowrap">' + nullValueTransfer(Highcharts.pick(point.point.value, point.y)) +
            series.options.tooltip.valueSuffix + '</td></tr>';
    });

    // Add wind
    var windSpeedValue;
    if (this.windSpeeds[index] == null || this.windSpeeds[index] == "--") {
        windSpeedValue = "--";
    }
    else {
        windSpeedValue = Highcharts.numberFormat(this.windSpeeds[index], 1);
    }
    ret += '<tr><td style="vertical-align: top">\u25CF 风</td><td style="white-space:nowrap">' + nullValueTransfer(this.windDirectionNames[index]) +
        '<br>' + nullValueTransfer(this.windSpeedNames[index]) + ' (' + windSpeedValue + ' m/s)</td></tr>';

    // Close
    ret += '</table>';


    return ret;
};

Meteogram.prototype.getChartOptions = function () {
    var meteogram = this;
    return {
        chart: {
            renderTo: this.container
        },
        lang: {
            contextButtonTitle: '导出图片',
            loading: '加载中',
            noData: '没有数据'
        },
        exporting: {
            buttons: {
                contextButton: {
                    menuItems: null,
                    onclick: function () {
                        this.exportChartLocal();
                    }
                }
            },
            filename: this.title,
            sourceHeight: $("#" + this.container).height(),
            sourceWidth: $("#" + this.container).width()
        },
        credits: {
            enabled:false
        },
        title: {
            text: this.title
        },
        xAxis: [{
            categories: this.timepoints,

            offset: 30
        }],
        yAxis: [{ // Primary yAxis
            labels: {
                format: '{value}°C',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            title: {
                text: '温度',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            }
        }, { // Secondary yAxis
            title: {
                text: '降水量',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }

            },
            labels: {
                format: '{value}mm',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            opposite: true
        }, { // Air pressure
            title: {
                text: '气压',
                style: {
                    color: Highcharts.getOptions().colors[2]
                }

            },
            labels: {
                format: '{value}hPa',
                style: {
                    color: Highcharts.getOptions().colors[2]
                }
            },
            opposite: true
        }],
        tooltip: {
            shared: true,
            crosshairs: true,
            useHTML: true,
            formatter: function () {
                return meteogram.tooltipFormatter(this);
            }
        },
        legend: {
            align: 'center',
            verticalAlign: 'bottom'
        },

        series: [{
            name: '温度',
            type: 'spline',
            yAxis: 0,
            zIndex: 1,
            color: Highcharts.getOptions().colors[1],
            data: this.temperatures,
            tooltip: {
                valueSuffix: '°C'
            }
        }, {
            name: '降雨量',
            type: 'column',
            yAxis: 1,
            color: Highcharts.getOptions().colors[0],
            data: this.rainfalls,
            tooltip: {
                valueSuffix: ' mm'
            }

        }, {
            name: '气压',
            zIndex: 1,
            color: Highcharts.getOptions().colors[2],
            data: this.pressures,
            marker: {
                enabled: true
            },
            shadow: false,
            tooltip: {
                valueSuffix: ' hPa'
            },
            dashStyle: 'shortdot',
            yAxis: 2
        }]
    }
};

Meteogram.prototype.onChartLoad = function (chart) {

    this.drawWindArrows(chart);
    //this.drawBlocksForWindArrows(chart);
};

Meteogram.prototype.createChart = function () {
    var meteogram = this;
    this.chart = new Highcharts.Chart(this.getChartOptions(), function (chart) {
        meteogram.onChartLoad(chart);
    });
};


Meteogram.prototype.createNoDataChart = function () {
    var meteogram = this;

    var nodataOptions = {
        lang: {
            contextButtonTitle: '导出图片',
            loading: '加载中',
            noData: '没有数据'
        },
        exporting: {
            buttons: {
                contextButton: {
                    menuItems: null,
                    onclick: function () {
                        this.exportChartLocal();
                    }
                }
            },
            filename: this.title,
            sourceHeight: $("#" + this.container).height(),
            sourceWidth: $("#" + this.container).width()
        },
        chart: {
            renderTo: meteogram.container,
            height: meteogram.height,
            width: meteogram.width
        },
        title: {
            text: '暂无数据'
        },
        series: [{
            type: 'line',
            name: meteogram.name,
            data: []
        }],
        lang: {
            noData: "Nichts zu anzeigen"
        },
        noData: {
            style: {
                fontWeight: 'bold',
                fontSize: '15px',
                color: '#303030'
            }
        }
    };
    this.chart = new Highcharts.Chart(nodataOptions, function (chart) {
        meteogram.onChartLoad(chart);
    });
};


Meteogram.prototype.initData = function () {
    var meteogram = this;
    var data = this.jsonData;
    var dataLength = data.length;

    if (dataLength > 0) {
        for (var i = 0; i < dataLength; i++) {
            var timePoint = new Date(data[i].TimePoint.replace("-", "/").replace("-", "/")).format(meteogram.timePointFormat);
            meteogram.timepoints.push(timePoint);
            meteogram.temperatures.push({ y: data[i].AirTemperature-0, index: i });

            var rainfall = data[i].Rainfall;
            if (rainfall == null) {
                rainfall = 0;
            }
            meteogram.rainfalls.push(rainfall-0);
            meteogram.pressures.push(data[i].Pressure-0);
            meteogram.windSpeeds.push(data[i].WindSpeed-0);
            meteogram.windSpeedNames.push(GetWindLevel(data[i].WindSpeed));
            meteogram.windDirections.push(data[i].WindDirection-0);
            meteogram.windDirectionNames.push(GetWindDirectionName(data[i].WindDirection));
        }
    }
    else {
        meteogram.createNoDataChart();
    }


    this.createChart();
};